# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_ssl_xmlrpc_client.py 
@time: 2019/7/12 下午4:00
"""
'''
创建ssl证书的XMLRPC客户端
'''
from xmlrpc.client import SafeTransport, ServerProxy
import ssl


class VerifyCertSafeTransport(SafeTransport):
    def __init__(self, cafile, certfile=None, keyfile=None):
        SafeTransport.__init__(self)
        self._cafile = cafile
        self._certfile = certfile
        self._keyfile = keyfile

    def get_ssl_context(self):

        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.load_verify_locations(self._cafile)
        if self._certfile:
            context.load_cert_chain(certfile=self._certfile, keyfile=self._keyfile)
        context.verify_mode = ssl.CERT_REQUIRED

        return context

if __name__ == '__main__':
    KEYFILE='client_key.pem'
    CERTFILE='client_cert.pem'
    CA_CERTS='server_cert.pem'
    v=VerifyCertSafeTransport(keyfile=KEYFILE, certfile=CERTFILE, cafile=CA_CERTS)
    s = ServerProxy('https://localhost:15000',context=v.get_ssl_context(), allow_none=True)
    s.set('foo', 'bar')
    print(s.get('foo'))
    s.set('spam', [1, 2, 3])
    print(s.keys())
    print(s.get('spam'))
    s.delete('spam')
    print(s.exists('spam'))
